<?php

namespace app\api\controller;

use app\admin\model\yl\Member;
use app\admin\model\yl\Pay;
use app\admin\model\yl\price\Log;
use app\api\library\BetcatpayApi;
use app\api\library\Pay666Api;
use app\api\library\SpeedlypayApi;
use app\api\library\SunpayApi;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Writer\PngWriter;
use fast\Random;
use think\Config;
use think\Db;
use think\Exception;
use think\Validate;

/**
 * 会员接口
 */
class Members extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        $this->get_member_info();
    }

    /**
     * 个人信息
     */
    public function index()
    {

        //$this->member['code_img'] = $this->QRcode($this->member['code']);
        $this->member['code_url'] = CC('web_url') . '#/pages/register/register?code=' . $this->member['code'];
        $this->member['price'] = num_str($this->member['price'], 2);
        unset($this->member['password']);
        unset($this->member['security_password']);

        $this->member['withdrawn'] = $this->member['price'];//可提现金额

//        $where = ['yingkui' => 1, 'member_id' => $this->member['id']];
//        $today_income = Db::name('yl_product_order')->where($where)
//            ->where('sale_time','>=', strtotime(date('Y-m-d')))
//            ->field('SUM(money) money')->find();
//        $this->member['today_income'] = $today_income['money']??0;//今日收入

//        $dayOfWeek = date('N');
//        $daysToMonday = $dayOfWeek - 1;
//        $monday = date('Y-m-d', strtotime("-$daysToMonday days"));
//        $data = Db::name('yl_product_order')->where($where)
//            ->where('sale_time','>=', strtotime($monday))
//            ->field('SUM(money) money')->find();
//        $this->member['week_profit'] = $data['money']??0;//周收入

//        $thismonth = strtotime(date('Y-m-01'));
//        $data = Db::name('yl_product_order')->where($where)
//            ->where('sale_time','>=', $thismonth)
//            ->field('SUM(money) money')->find();
//        $this->member['month_profit'] = $data['money']??0;//月收入

//        $data = Db::name('yl_product_order')->where($where)
//            ->where('sale_time','between', [strtotime(date('Y-m-01', strtotime('-1 month'))), $thismonth-1])
//            ->field('SUM(money) money')->find();
//        $this->member['month_profit'] = $data['money']??0;//月收入
//        $this->member['lastmonth_profit'] = $data['money']??0;//上月收入
//
//        $data = Db::name('yl_product_order')->where($where)->field('SUM(money) money')->find();
//        $this->member['all_income'] = $data['money']??0;//总收入

        // 银行卡钱包绑定
//        $wallet = Db::name('yl_wallet')->where('member_id', $this->member['id'])->field('type')->column('type');
//        $this->member['wallet_bank'] = in_array(1, $wallet) ? 1 : 0;
//        $this->member['wallet_usdt'] = in_array(2, $wallet) ? 1 : 0;
//        $this->member['sql'] = Db::name('yl_product_order')->where($where)->field('SUM(money) money')->select(false);
        $member = $this->member;
        $data = [
            'id' => $member['id'],
            'user' => $member['user'],
            'create_time' => date('Y-m-d H:i:s', $member['create_time']),
            'login_time' => date('Y-m-d H:i:s', $member['login_time']),
            'integral' => $member['integral'],
            'status' => $member['status'],
        ];
        $vips = Db::name('yl_vips')->where(['is_vip' => 1, 'member_id' => $member['id']])->find();
        if (!empty($vips)) {
            $vip_config_info = Db::name('yl_vip_config')->where(['id' => $vips['vip_config_id']])->find();
            $data['vip_name'] = $vip_config_info['name'] . "会员";
            $data['vip_endtime'] = date('Y-m-d H:i:s', $vips['endtime']);

        }
        $this->success('successful', $data);
    }

    /***
     * 生成二维码
     *
     */
    public function QRcode($code)
    {
        $writer = new PngWriter();
        $url = CC('web_url') . '#/pages/register/register?code=' . $code;
        //创建实例
        $qrCode = QrCode::create($url)
            ->setSize(300)
            ->setMargin(10)
            ->setEncoding(new Encoding('UTF-8'))
            ->setErrorCorrectionLevel(new ErrorCorrectionLevelHigh());
        $result = $writer->write($qrCode);
        header('Content-Type: ' . $result->getMimeType());
        $result->saveToFile(ROOT_PATH . '/public/uploads/qrcode/' . $code . '.png');
        return $this->site_url . '/uploads/qrcode/' . $code . '.png';
    }

    /**
     * 开通会员
     */
    public function buy_vip()
    {
        $member = $this->member;
        $vip_config_id = $this->request->param('vip_config_id');
        $vip_config = Db::name('yl_vip_config')->where(['id' => $vip_config_id])->find();
        $vip_price = $vip_config['price'];
        Db::startTrans();
        try {
//            if ($member['price'] >= $vip_price){
//                $member['price'] = bcsub($member['price'],$vip_price,5);
//                $member['frozen_price'] = bcadd($member['frozen_price'],$vip_price,5);
//                $order_no = "V".date('YmdHis').rand(0,10).rand(0,10).rand(0,10).rand(0,10);
//                Db::name('yl_member')->update([
//                    'id'=> $member['id'],
//                    'price' => $member['price'],
//                    'frozen_price' => $member['frozen_price'],
//                ]);
//                Db::name('product_vip')->insertGetId([
//                    'order_no' => $order_no,
//                    'member_id' => $member['id'],
//                    'vip_config_id' => $vip_config_id,
//                    'price' => $vip_price,
//                    'create_time' => time(),
//                ]);
//            }else{
//                $this->error('余额不足');
//            }

            $order_no = "V" . date('YmdHis') . rand(0, 10) . rand(0, 10) . rand(0, 10) . rand(0, 10);
            Db::name('product_vip')->insertGetId([
                'order_no' => $order_no,
                'member_id' => $member['id'],
                'vip_config_id' => $vip_config_id,
                'price' => $vip_price,
                'create_time' => time(),
            ]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('successful');
    }

    /**
     * 拼多多
     * 商品列表
     */
    public function get_pdd_list()
    {

        $goods_field = "id,goods_id,image_url,title,sales_num,price,coupons_price,
        evaluation,sales24_num,freight,positive_review_rate,listing_time,shop_name,
        shop_goods_num,shop_rating,cate_name,cate1_id,cate2_id,cate3_id,cate4_id,detail_url";
        $listRows = $this->request->param('listRows', 15);
        $goods_id = $this->request->param('goods_id');
        $title = $this->request->param('title');
        //分类
        $cate1_id = $this->request->param('cate1_id');
        $cate2_id = $this->request->param('cate2_id');
        $cate3_id = $this->request->param('cate3_id');
        $cate4_id = $this->request->param('cate4_id');
        //商品总销量
        $sales_min = $this->request->param('sales_min');
        $sales_max = $this->request->param('sales_max');
        //价格
        $price_min = $this->request->param('price_min');
        $price_max = $this->request->param('price_max');
        //劵后价
        $coupons_price_min = $this->request->param('coupons_price_min');
        $coupons_price_max = $this->request->param('coupons_price_max');
        //店铺名称
        $shop_name = $this->request->param('shop_name');

        $pddss_list = Db::name('pddss');
        if (!empty($goods_id)) {
            $pddss_list = $pddss_list->where('goods_id', $goods_id);
        }
        if (!empty($title)){
            $pddss_list = $pddss_list->where('title', 'like',"%".$title."%");
        }
        if (!empty($cate1_id)){
            $pddss_list = $pddss_list->where('cate1_id', $cate1_id);
        }
        if (!empty($cate2_id)){
            $pddss_list = $pddss_list->where('cate2_id', $cate2_id);
        }
        if (!empty($cate3_id)){
            $pddss_list = $pddss_list->where('cate3_id', $cate3_id);
        }
        if (!empty($cate4_id)){
            $pddss_list = $pddss_list->where('cate4_id', $cate4_id);
        }
        //商品总销量
        //商品最小销量
        if (!empty($sales_min)){
            $pddss_list = $pddss_list->where('sales_num',">=",$sales_min);
        }
        //商品最大销量
        if (!empty($sales_max)){
            $pddss_list = $pddss_list->where('sales_num',"<=",$sales_max);
        }
        //价格
        //价格最小
        if (!empty($price_min)){
            $pddss_list = $pddss_list->where('price',">=",$price_min);
        }
        //价格最大
        if (!empty($price_max)){
            $pddss_list = $pddss_list->where('price',"<=",$price_max);
        }
        //劵后价
        //劵后价最小
        if (!empty($coupons_price_min)){
            $pddss_list = $pddss_list->where('coupons_price',">=",$coupons_price_min);
        }
        //劵后价最大
        if (!empty($coupons_price_max)){
            $pddss_list = $pddss_list->where('coupons_price',"<=",$coupons_price_max);
        }
        //店铺名称
        if (!empty($shop_name)){
            $pddss_list = $pddss_list->where('shop_name',"like","%".$shop_name."%");
        }

        $pddss_list = $pddss_list->field($goods_field)->order('id desc')->paginate($listRows);
        $pdd_cate_list = Db::name('pdd_cate')->select();
        $rows = $pddss_list->items();
        foreach ($rows as &$row){
            foreach ($pdd_cate_list as $pdd_cate_item){
                if ($row['cate1_id'] == $pdd_cate_item['cat_id']) {
                    $row['cate1_name'] = $pdd_cate_item['cat_name'];
                }
                if ($row['cate2_id'] == $pdd_cate_item['cat_id']) {
                    $row['cate2_name'] = $pdd_cate_item['cat_name'];
                }
                if ($row['cate3_id'] == $pdd_cate_item['cat_id']) {
                    $row['cate3_name'] = $pdd_cate_item['cat_name'];
                }
                if ($row['cate4_id'] == $pdd_cate_item['cat_id']) {
                    $row['cate4_name'] = $pdd_cate_item['cat_name'];
                }
            }
        }
        $result = [
            'total' => $pddss_list->total(),
            'per_page' => $pddss_list->listRows(),
            'current_page'=> $pddss_list->currentPage(),
            'last_page' => $pddss_list->lastPage(),
            'data' => $rows
        ];

        $this->success('successful', $result);
    }

    /**
     * 分类列表
     */
    public function get_pdd_cate_list()
    {
        $leaf = intval($this->request->param('leaf',0));
        $parent_cat_id = intval($this->request->param('parent_cat_id'));
        $listRows = $this->request->param('listRows',15);
        $new_leaf = [1,2,3,4];
        if (!in_array($leaf,[0,1,2,3,4])){
            $this->error('请选择正确的分类等级');
        }
        $pdd_list = Db::name('pdd_cate')
            ->field('id,cat_id,cat_name,leaf,parent_cat_id');
        if(in_array($leaf,$new_leaf)){
            $pdd_list = $pdd_list->where('leaf',$leaf);
        }
        if (!empty($parent_cat_id)){
            $pdd_list = $pdd_list->where('parent_cat_id',$parent_cat_id);
        }
        $pdd_list = $pdd_list->paginate($listRows);
        $this->success('successful',$pdd_list);
    }

    /**
     * 收藏列表
     */
    public function get_collect_list()
    {
        $member = $this->member;
        $listRows = $this->request->param('listRows', 15);
        $collect_list = Db::name('collect')
            ->where('member_id', $member['id'])
            ->paginate($listRows)
            ->each(function ($item) {
                $item['create_time'] = !empty($item['create_time']) ? date('Y-m-d H:i:s', $item['create_time']) : "";
                return $item;
            });
        $rows = $collect_list->items();
        $pdd_goods_id = [];
        $dd_goods_id = [];
        foreach ($rows as &$row) {
            switch ($row['type']){
                case 1:
                    $pdd_goods_id[] = $row['other_id'];
                    break;
                case 2:
                    $dd_goods_id[] = $row['other_id'];
                    break;
            }
        }
        //拼多多
        $pddss_list = Db::name('pddss')
            ->alias("a")
            ->field("a.id as aid,goods_id,image_url,title,sales_num,price,coupons_price,evaluation,sales24_num,
                          freight,positive_review_rate,listing_time,shop_name,shop_goods_num,shop_rating,cate_name
                          ,cate1_id,cate2_id,cate3_id,cate4_id,detail_url")
            ->where('a.id','in',$pdd_goods_id)
            ->select();
        $pdd_cate_list = Db::name('pdd_cate')->field("cat_id,cat_name")->select();
        foreach ($pddss_list as &$row){
            foreach ($pdd_cate_list as $pdd_cate_item){
                if ($row['cate1_id'] == $pdd_cate_item['cat_id']) {
                    $row['cate1_name'] = $pdd_cate_item['cat_name'];
                }
                if ($row['cate2_id'] == $pdd_cate_item['cat_id']) {
                    $row['cate2_name'] = $pdd_cate_item['cat_name'];
                }
                if ($row['cate3_id'] == $pdd_cate_item['cat_id']) {
                    $row['cate3_name'] = $pdd_cate_item['cat_name'];
                }
                if ($row['cate4_id'] == $pdd_cate_item['cat_id']) {
                    $row['cate4_name'] = $pdd_cate_item['cat_name'];
                }
            }
        }
        //抖店
        $dd_list = Db::name('ddss')
            ->alias("a")
            ->field("a.id as aid,goods_id,image_url,title,sales_num,price,coupons_price,evaluation,sales24_num,
                          freight,positive_review_rate,listing_time,shop_name,shop_goods_num,shop_rating
                          ,cate1_id,cate2_id,cate3_id,detail_url")
            ->where('a.id','in',$dd_goods_id)
            ->select();
        $dd_category = Db::name('dd_category')->field("category_id,name")->select();
        foreach ($dd_list as &$ddss_item) {
            foreach ($dd_category as $dd_category_item) {
                if ($ddss_item['cate1_id'] == $dd_category_item['category_id']) {
                    $ddss_item['cate1_name'] = $dd_category_item['name'];
                }
                if ($ddss_item['cate2_id'] == $dd_category_item['category_id']) {
                    $ddss_item['cate2_name'] = $dd_category_item['name'];
                }
                if ($ddss_item['cate3_id'] == $dd_category_item['category_id']) {
                    $ddss_item['cate3_name'] = $dd_category_item['name'];
                }
            }
            $ddss_item['price'] = $ddss_item['price']*0.01;
            $ddss_item['coupons_price'] = $ddss_item['coupons_price']*0.01;
        }
        foreach ($rows as &$row) {
            switch ($row['type']) {
                case 1:
                    foreach ($pddss_list as $pddss_item) {
                        if ($row['other_id'] == $pddss_item['aid']) {
                            $row['info'] = $pddss_item;
                        }
                    }
                    break;
                case 2:
                    foreach ($dd_list as $dd_item) {
                        if ($row['other_id'] == $dd_item['aid']) {
                            $dd_item['goods_id'] = (string)$dd_item['goods_id'];
                            $row['info'] = $dd_item;
                        }
                    }
                    break;
            }
        }



        $result = [
            'total' => $collect_list->total(),
            'per_page' => $collect_list->listRows(),
            'current_page' => $collect_list->currentPage(),
            'last_page' => $collect_list->lastPage(),
            'data' => $rows
        ];
        $this->success('successful', $result);
    }

    /**
     * 收藏
     */
    public function set_collect()
    {
        $member = $this->member;
        $type = $this->request->param('type');
        $other_id = $this->request->param('other_id');
        if (empty($type) || empty($other_id)) {
            $this->success('收藏类型或商品未选择');
        }
        $collect_list = Db::name('collect')->where([
            'member_id' => $member['id'],
            'type' => $type,
        ])->select();
        foreach ($collect_list as $collect){
            if ($collect['other_id'] == $other_id){
                $this->error('该商品已经收藏过了');
            }
        }
        $result = Db::name('collect')->insertGetId([
            'type' => $type,
            'member_id' => $member['id'],
            'other_id' => $other_id,
            'create_time' => time(),
        ]);
        if (empty($result)) {
            $this->error('收藏失败，请重试');
        }
        $this->success('successful', $result);
    }

    /**
     * 取消收藏
     */
    public function del_collect()
    {
        $member = $this->member;
        $id = intval($this->request->param('id'));
        if (empty($id)) {
            $this->error('请先选择商品,在取消收藏');
        }
        $result = Db::name('collect')
            ->where('member_id', $member['id'])
            ->delete(['id' => $id]);
        if (empty($result)) {
            $this->error('取消收藏失败，请先收藏,在取消收藏');
        }
        $this->success('successful', $result);
    }

    /**
     * 抖店的商品列表
     */
    public function get_dd_list()
    {
        $goods_field = "id,goods_id,image_url,title,sales_num,price,coupons_price,
        evaluation,sales24_num,freight,positive_review_rate,listing_time,shop_name,
        shop_goods_num,shop_rating,cate1_id,cate2_id,cate3_id,detail_url";
        $listRows = $this->request->param('listRows', 15);
        $goods_id = $this->request->param('goods_id');
        $title = $this->request->param('title');
        //分类
        $cate1_id = $this->request->param('cate1_id');
        $cate2_id = $this->request->param('cate2_id');
        $cate3_id = $this->request->param('cate3_id');
        //商品总销量
        $sales_min = $this->request->param('sales_min');
        $sales_max = $this->request->param('sales_max');
        //价格
        $price_min = $this->request->param('price_min');
        $price_max = $this->request->param('price_max');
        //劵后价
        $coupons_price_min = $this->request->param('coupons_price_min');
        $coupons_price_max = $this->request->param('coupons_price_max');
        //店铺名称
        $shop_name = $this->request->param('shop_name');
        $ddss_list = Db::name('ddss');
        if (!empty($goods_id)) {
            $ddss_list = $ddss_list->where('goods_id', $goods_id);
        }
        if (!empty($title)){
            $ddss_list = $ddss_list->where('title', 'like',"%".$title."%");
        }
        if (!empty($cate1_id)){
            $ddss_list = $ddss_list->where('cate1_id', $cate1_id);
        }
        if (!empty($cate2_id)){
            $ddss_list = $ddss_list->where('cate2_id', $cate2_id);
        }
        if (!empty($cate3_id)){
            $ddss_list = $ddss_list->where('cate3_id', $cate3_id);
        }

        //商品总销量
        //商品最小销量
        if (!empty($sales_min)){
            $ddss_list = $ddss_list->where('sales_num',">=",$sales_min);
        }
        //商品最大销量
        if (!empty($sales_max)){
            $ddss_list = $ddss_list->where('sales_num',"<=",$sales_max);
        }
        //价格
        //价格最小
        if (!empty($price_min)){
            $price_min = bcmul($price_min,100,2);
            $ddss_list = $ddss_list->where('price',">=",$price_min);
        }
        //价格最大
        if (!empty($price_max)){
            $price_max = bcmul($price_max,100,2);
            $ddss_list = $ddss_list->where('price',"<=",$price_max);
        }
        //劵后价
        //劵后价最小
        if (!empty($coupons_price_min)){
            $coupons_price_min = bcmul($coupons_price_min,100,2);
            $ddss_list = $ddss_list->where('coupons_price',">=",$coupons_price_min);
        }
        //劵后价最大
        if (!empty($coupons_price_max)){
            $coupons_price_max = bcmul($coupons_price_max,100,2);
            $ddss_list = $ddss_list->where('coupons_price',"<=",$coupons_price_max);
        }
        //店铺名称
        if (!empty($shop_name)){
            $ddss_list = $ddss_list->where('shop_name',"like","%".$shop_name."%");
        }
        $ddss_list = $ddss_list->field($goods_field)->order('id desc')->paginate($listRows);
        $dd_category = Db::name('dd_category')->select();
        $rows = $ddss_list->items();
        foreach ($rows as &$ddss_item) {
            foreach ($dd_category as $dd_category_item) {
                if ($ddss_item['cate1_id'] == $dd_category_item['category_id']) {
                    $ddss_item['cate1_name'] = $dd_category_item['name'];
                }
                if ($ddss_item['cate2_id'] == $dd_category_item['category_id']) {
                    $ddss_item['cate2_name'] = $dd_category_item['name'];
                }
                if ($ddss_item['cate3_id'] == $dd_category_item['category_id']) {
                    $ddss_item['cate3_name'] = $dd_category_item['name'];
                }
            }
            $ddss_item['coupons_price'] = bcmul($ddss_item['coupons_price'],0.01,2);
            $ddss_item['price'] = bcmul($ddss_item['price'],0.01,2);
            $ddss_item['goods_id'] = (String)$ddss_item['goods_id'];
        }
        $result = [
            'total' => $ddss_list->total(),
            'per_page' => $ddss_list->listRows(),
            'current_page'=> $ddss_list->currentPage(),
            'last_page' => $ddss_list->lastPage(),
            'data' => $rows
        ];
        $this->success('successful', $result);
    }

    /**
     * 抖店的商品分类列表
     */
    public function get_dd_cate_list()
    {
        $level = intval($this->request->param('level', 0));
        $parent_cat_id = intval($this->request->param('parent_cat_id'));
        $listRows = $this->request->param('listRows', 15);
        $new_level = [1, 2, 3];
        if (!in_array($level, [0,1,2,3])) {
            $this->error('请选择正确的分类等级');
        }
        $dd_list = Db::name('dd_category')
            ->field('id,category_id,name,level,parent_id');
        if(in_array($level,$new_level)){
            $dd_list = $dd_list->where('level',$level);
        }
        if (!empty($parent_cat_id)){
            $dd_list = $dd_list->where('parent_id',$parent_cat_id);
        }
        $dd_list = $dd_list->paginate($listRows);
        $this->success('successful', $dd_list);
    }
}